package cn.zyy.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * JDBC工具类：使用德鲁伊连接池
 */
public final class JDBCUtil {
    private static DataSource dataSource = null;

    public JDBCUtil() {}
    //初始化资源
    static {
        try {
            //加载文件初始化参数
            InputStream ins = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            Properties ps = new Properties();
            ps.load(ins);
            //创建德鲁伊连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(ps);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取数据库连接池的方法
    public static DataSource getDataSource() {
        return dataSource;
    }
    //获取连接  从数据库连接池中获取
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //释放资源
    public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
        try {
            if (rs != null) {//避免空指针
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
